/*
 * Copyright (c) 2010, Oracle. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of Oracle nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

package medialibrary.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;
import medialibrary.persistence.Membre;


/**
 * The sevelet class to insert Membre into database
 */
@WebServlet(name="CreateMemberServlet", urlPatterns={"/CreateMember"})
public class CreateMemberServlet extends HttpServlet {
    
    @PersistenceUnit
    //The emf corresponding to 
    private EntityManagerFactory emf;  
    
    @Resource
    private UserTransaction utx;

    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException {
        
        assert emf != null;  //Make sure injection went through correctly.
        EntityManager em = null;
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
            HttpSession session = request.getSession();
        
        try {
            PrintWriter out = response.getWriter();
                    try{    
                        if(session.getAttribute("usertype")!="admin"){
                          response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/disconnect.jsp") );
                        }
                    }catch(Exception e){}            
            //Get the data from user's form
            //String id     = (String) request.getParameter("id");
            String name     = (String) request.getParameter("name");
            String surname  = (String) request.getParameter("surname");
            String birthdate  = (String) request.getParameter("birthdate");
            String login    = (String) request.getParameter("login");
            //Do a test on the size and keep 7 letters 
           String password = (String) request.getParameter("password");
            String email    = (String) request.getParameter("email");
            
            Date today=new Date(System.currentTimeMillis());
            Date birthDate;
            
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
                birthDate=dateFormat.parse(birthdate);
            } catch(Exception e) {
                birthDate=new Date(System.currentTimeMillis());
            }
            
            //Create a person instance out of it
            Membre person = new Membre(surname, name, birthDate, login, password, email, today);
            //begin a transaction
            utx.begin();
            //create an em. 
            //Since the em is created inside a transaction, it is associsated with the transaction
            em = emf.createEntityManager();
            
            
            //persist the person entity
            try {  
                em.persist(person);
            } catch(Exception e) {
                out.println(e);
                throw(e);
            }         
            
            //commit transaction which will trigger the em to 
            //commit newly created entity into database
            utx.commit();
            response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/AdminUI.jsp") );
        } catch (Exception ex) {            
            throw new ServletException(ex);
            
        } finally {
            //close the em to release any resources held up by the persistebce provider
            if(em != null) {
                em.close();
            }
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
